import { Context, Next } from 'koa';

export default async function errorHandler(ctx: Context, next: Next) {
    try {
        await next();
    } catch (err: any) {
        const status = err.status || 500;
        ctx.status = status;
        ctx.body = {
            code: status,
            message: err.message || '服务器内部错误',
            // 开发环境展示 stack
            ...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
        };
        console.error('[Error]', ctx.method, ctx.url, err);
    }
}